package fr.poc.rest.job;

import java.util.List;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;


//import org.apache.commons.collections.ListUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

//import com.netflix.appinfo.InstanceInfo;
//import com.netflix.discovery.DiscoveryManager;

@Component
public class PocUsingEurekaRemoteService {

	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private DiscoveryClient springCloudDiscoveryClient ;
	
	
	private Client client = ClientBuilder.newClient();

	@Scheduled(initialDelay = 30000, fixedDelay = 10000)
	public void callHello() {
		// String uri = targetBaseUrl + "/hello";

		// eureka
//		String vipAddress = configInstance.getStringProperty(
//				"eureka.vipAddressTarget", "pocserviceB.mydomain.net").get();
//		InstanceInfo nextServerInfo = DiscoveryManager.getInstance()
//				.getDiscoveryClient()
//				.getNextServerFromEureka(vipAddress, false);
		
		//spring-cloud without Ribbon
		String vipAddress  = "pocserviceB.mydomain.net";
		List<ServiceInstance> services =  springCloudDiscoveryClient.getInstances(vipAddress);
		String uri=null, greetings=null;
		
		if (!services.isEmpty()) {
			ServiceInstance service = services.get(0);

			uri = "http://" + service.getHost() + ":" + service.getPort()
					+ "/rest/hello";

			logger.info(">>callHello>>>>vipAdress={} , uri={}", vipAddress, uri);

			WebTarget target = client.target(uri);
			greetings = target.request(MediaType.APPLICATION_JSON_TYPE).get(
					String.class);
		}
		
		logger.info(">>callHello>>>> URI:{} / REPONSE:{}", uri, greetings);

	}

}
